package cn.com.connected.common.utils;

import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.vo.wechat.ErrorInfo;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Import;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author： HuLanHui
 * @Data： 2018.8.17 13:16
 * @Description：
 */
@Import(OkHttp3ClientHttpRequestFactory.class)
@Component
public class HttpUtil {

    private Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public <T> T get(String url, Class<T> clazz){
        String json = null;
        try {
            logger.info("httpUtil request url：{}",url);
            Request request = new Request.Builder().url(url).build();
            Response response = okHttpClient().newCall(request).execute();
            json = response.body().string();
            logger.info("httpUtil response body：{}",json);
        } catch (IOException e) {
            logger.error("httpUtil error：{}",e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_FAIL,json);
        }
        ErrorInfo obj = JSONObject.parseObject(json,ErrorInfo.class);
        if(obj!=null && StringUtils.isNotEmpty(obj.getErrcode()) && !obj.getErrcode().equals("0")){
            throw new BusinessException(ErrorCode.SYSTEM_FAIL,json);
        }else{
            return JSONObject.parseObject(json,clazz);
        }
    }

    public <T> T post(String url, Map params, Class<T> clazz){
        String json = params==null?null:JSONObject.toJSONString(params);
        try {
            logger.info("httpUtil request url：{}",url);
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = okHttpClient().newCall(request).execute();
            json = response.body().string();
            logger.info("httpUtil response body：{}",json);
        } catch (IOException e) {
            logger.error("httpUtil error：{}",e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_FAIL,json);
        }
        ErrorInfo obj = JSONObject.parseObject(json,ErrorInfo.class);
        if(obj!=null && StringUtils.isNotEmpty(obj.getErrcode()) && obj.getErrcode().equals("87014")){
            throw new BusinessException(ErrorCode.CONTENT_ERROR,"内容含有违法违规内容");
        }else if(obj!=null && StringUtils.isNotEmpty(obj.getErrcode()) && !obj.getErrcode().equals("0")){
            throw new BusinessException(ErrorCode.SYSTEM_FAIL,json);
        }else{
            return JSONObject.parseObject(json,clazz);
        }
    }


    public OkHttpClient okHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
        return builder.build();
    }
}
